package ccm.component.image;

import java.awt.event.ComponentEvent;
import java.awt.event.ComponentListener;
import java.awt.image.BufferedImage;

public class AutoResizeableImageJPanel extends ResizeableImageJPanel implements ComponentListener
{
    /**
     * 保存缩放的最大比例
     */
    protected float maxResizeRate;

    public AutoResizeableImageJPanel()
    {
        this(null);
    }

    public AutoResizeableImageJPanel(BufferedImage image)
    {
        super(image);
        addComponentListener(this);
        maxResizeRate=1;
        updateResizeRate();
        updateImg();
    }

    /**
     * 更新缩放的比例
     */
    protected void updateResizeRate()
    {
        if(image==null)
        {return;}
        int w=(int)(image.getWidth()*maxResizeRate);
        int h=(int)(image.getHeight()*maxResizeRate);
        if(w>getWidth()&&getWidth()!=0)
        {w=getWidth();}
        if(h>getHeight()&&getHeight()!=0)
        {h=getHeight();}
        resizeRate=Math.min(1.0f*w/image.getWidth(),1.0f*h/image.getHeight());
    }

    /**
     * 设置图片
     *
     * @param image 图片
     */
    public void setImage(BufferedImage image)
    {
        this.image=image;
        updateResizeRate();
        updateImg();
        revalidate();
    }

    /**
     * 设置缩放的最大比例
     *
     * @param resizeRate 缩放的最大比例
     */
    public void setResizeRate(float resizeRate)
    {
        this.maxResizeRate=resizeRate;
        updateResizeRate();
        updateImg();
    }

    /**
     * 组件尺寸发生变化的时候自动缩放图片
     */
    public void componentResized(ComponentEvent e)
    {
        if(e.getSource().equals(this))
        {
            updateResizeRate();
            updateImg();
        }
    }

    public void componentMoved(ComponentEvent e)
    {

    }

    public void componentShown(ComponentEvent e)
    {

    }

    public void componentHidden(ComponentEvent e)
    {

    }
}
